﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SharpSoft.WPF.Controls
{
    /// <summary>
    /// 2D游戏面板
    /// </summary>
    public abstract class Game2d : Canvas
    {
        static Game2d()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Game2d), new FrameworkPropertyMetadata(typeof(Game2d)));
        }
        private System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
        protected readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        public Game2d()
        {
            timer.Interval = TimeSpan.FromSeconds(1.0 / 60.0D);
            timer.Tick += OnFrame;
            this.OnInit();
        }

        public int Fps
        {
            get { return (int)GetValue(FpsProperty); }
            private set { SetValue(FpsProperty, value); }
        }

        public static readonly DependencyProperty FpsProperty =
            DependencyProperty.Register("Fps", typeof(int), typeof(Game2d), new PropertyMetadata(0));



        protected void OnInit()
        {
            stopwatch.Start();

        }

        private long lastTicks = 0;
        private int frameCount = 0;//统计一秒内的帧数
        private long frameCountTime = 0;//距离上一次帧数统计经过的时间
        private void OnFrame(object _s, EventArgs _e)
        {
            var ticks = stopwatch.ElapsedTicks;
            var elapsed = ticks - lastTicks;
            this.lastTicks = ticks;
            frameCount++;
            frameCountTime += elapsed;
            if (frameCountTime >= 1000*10000)
            {
                frameCountTime = 0;
                this.Fps = frameCount;//统计一秒的帧数
                frameCount = 0;
            }
            this.OnUpdate(ticks, elapsed);
        }

        protected abstract void OnUpdate(long ticks, long lastFrameElapsed);

        public void Start()
        {
            timer.Start();

        }

        public void Pause()
        {
            timer.Stop();
        }

        public void Stop()
        {
            stopwatch.Stop();
            timer.Stop();
        }
    }
}
